package cc.magicjson.service.mybatis;


import cc.magicjson.entity.MyBatisUser;
import cc.magicjson.entity.User;

import cc.magicjson.mybatis.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceMyBatis {

    private final UserMapper userMapper;

    public UserServiceMyBatis(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Transactional("mybatisTransactionManager")
    public void createUser(MyBatisUser user) {
        userMapper.insert(user);
    }

    @Transactional(readOnly = true, transactionManager = "mybatisTransactionManager")
    public User getUserById(Long id) {
        return userMapper.findById(id);
    }

    @Transactional(readOnly = true, transactionManager = "mybatisTransactionManager")
    public Map<String, Object> getUserMapById(Long id) {
        Map<String, Object> result = userMapper.findByIdAsMap(id);
        System.out.println("Result from getUserMapById: " + result);
        return result;
    }

    @Transactional(readOnly = true, transactionManager = "mybatisTransactionManager")
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }

    @Transactional("mybatisTransactionManager")
    public void updateUser(MyBatisUser user) {
        userMapper.update(user);
    }

    @Transactional("mybatisTransactionManager")
    public void deleteUser(Long id) {
        userMapper.delete(id);
    }

    @Transactional(readOnly = true,transactionManager = "mybatisTransactionManager")
    public MyBatisUser findByIdWithAddress(Long id){
        return userMapper.findByIdWithAddress(id);
    }
}
